/**
 * Created by shudong.msd(风骐) on 2016/4/30.
 */

app.directive('resultSearchEngine',function(){

    return function(scope,ele,attr){
            var itemname = attr.itemname;
            //城市选择搜索框
            var starsBlood = new Bloodhound({
                identify: function(obj) { return obj.name; },
                datumTokenizer:  Bloodhound.tokenizers.obj.whitespace('name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: scope[itemname].alphabetList['全部']
            });

            var starTypeahead = ele.typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 1
                },
                {
                    name: 'full-data',
                    source: starsBlood,
                    display:'name',
                    limit: 5
                }
            );

            //绑定选择后以及焦点改变时发生的事件
            starTypeahead.bind('typeahead:change', function(ev, suggestion) {
                if(suggestion.trim()==""){
                    scope[itemname].list = scope[itemname].alphabetList['全部'];
                    if(!scope.$$phase){
                        scope.$apply();
                    }
                    return;
                }
                var tmpArr = [];
                var re =new RegExp("^"+suggestion+".*");
                var tmpL = scope[itemname].alphabetList['全部'];
                for(var i in tmpL){
                    if(re.test(tmpL[i].name))tmpArr.push(tmpL[i]);
                }
                if(tmpArr.length==0) tmpArr = scope[itemname].alphabetList['全部'];
                scope[itemname].list = tmpArr;
                if(!scope.$$phase){
                    scope.$apply();
                }
            });

            starTypeahead.bind('typeahead:select', function(ev, suggestion) {
                if(suggestion.name.trim()==""){
                    scope[itemname].list = scope[itemname].alphabetList['全部'];
                    if(!scope.$$phase){
                        scope.$apply();
                    }
                    return;
                }
                var tmpArr = [];
                var re =new RegExp("^"+suggestion.name+".*");
                var tmpL = scope[itemname].alphabetList['全部'];
                for(var i in tmpL){
                    if(re.test(tmpL[i].name))tmpArr.push(tmpL[i]);
                }
                if(tmpArr.length==0) tmpArr = scope[itemname].alphabetList['全部'];
                scope[itemname].list = tmpArr;
                if(!scope.$$phase){
                    scope.$apply();
                }
            });


    };
});